const Koa = require("koa");
const app = new Koa();
const views = require("koa-views");
const json = require("koa-json");
const onerror = require("koa-onerror");
// const bodyparser = require("koa-bodyparser");
const koaBody = require("koa-body");
const logger = require("koa-logger");
const path = require("path");

const index = require("./routes/index");

// error handler
onerror(app);

// middlewares
// app.use(
//   bodyparser({
//     enableTypes: ["json", "form", "text"],
//   })
// );
app.use(json());
app.use(logger());
app.use(require("koa-static")(__dirname + "/public"));
app.use(
  koaBody({
    enableTypes: ["json", "form", "text"],
    multipart: true,
    strict:false,
    formidable: {
      uploadDir: path.join(__dirname, "public"),
      maxFileSize: 200 * 1024 * 1024, // 设置上传文件大小最大限制，默认2M
      // 保留文件扩展名
      keepExtensions: true,
    },
  })
);

app.use(
  views(__dirname + "/views", {
    extension: "pug",
  })
);

// logger
app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

// routes
app.use(index.routes(), index.allowedMethods());

// error-handling
app.on("error", (err, ctx) => {
  console.error("server error", err, ctx);
});

module.exports = app;
